package com.monkey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.monkey.dao.mapper.TagMapper;
import com.monkey.dao.pojo.Tag;
import com.monkey.service.TagService;
import com.monkey.vo.Results;
import com.monkey.vo.TagsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author：monkey-L
 * @description: .
 * @date: 16:38 2021/10/4
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    public TagsVo copy(Tag tag){
        TagsVo tagVo = new TagsVo();
        BeanUtils.copyProperties(tag,tagVo);
        tagVo.setId(String.valueOf(tag.getId()));
        return tagVo;
    }
    public List<TagsVo> copyList(List<Tag> tagList){
        List<TagsVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }
    @Override
    public List<TagsVo> findTagsByArticleId(Long articleId) {
        //mybatis
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);

        return copyList(tags);
    }

    @Override
    public Results hots(int limit) {
        /**
         *功能描述:
         * 1.标签所拥有的文章数量最多， 就是最热标签
         * 2.查询根据tag_id 分组，计数，排序，取前面limit个
         * @author monkey-L
         * @date
         * @param
         * @return
         */
        List<Long> tagIds = tagMapper.findHotsTagIds(limit);
        if (CollectionUtils.isEmpty(tagIds)) {
            return Results.success(Collections.emptyList());
        }
//        需要的是tagId 和 tagName对象
        List<Tag> tagList = tagMapper.findTagsByTagId(tagIds);
        return Results.success(tagList);
    }

    @Override
    public Results findAll() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Tag::getTagName,Tag::getId);
        List<Tag> tagList = tagMapper.selectList(queryWrapper);
        return Results.success(copyList(tagList));
    }

    @Override
    public Results findAllDetail() {
        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<>());
        return Results.success(copyList(tagList));
    }

    @Override
    public Results findDetailById(Long id) {
        Tag tag = tagMapper.selectById(id);
        return Results.success(tag);
    }


}
